package edu.hawaii.myisern.action;

import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;

import static org.junit.Assert.assertEquals;
import org.junit.Test; 

/**
 * Test class for testing the LoginActionBean class.
 * @author Ben
 *
 */
public class TestLoginActionBean {

  /** The page title. */
  private String pageTitle = "MyISERN - Login";

  /** Get the test host. */
  private String testHost = System.getProperty("test.host");
  
  /**
   * Tests attempted break in without logging in.
   * @throws Exception if error occurs.
   */
  @Test
  public void testNotLoggedIn() throws Exception {
    WebConversation conversation = new WebConversation();

    // Go directly past the login screen URL.
    String Url = testHost + "myisern-fuchsia/displayTable.jsp";
    
    WebResponse response = conversation.getResponse(Url);

    // Attempt to run an ActionBean.
    WebForm pushForm = response.getFormWithID("PushForm");
    WebRequest pushRequest = pushForm.getRequest();
    response = conversation.getResponse(pushRequest);

    // Assure you are kicked to the login screen.
    assertEquals("Checking kick to login screen", pageTitle, response.getTitle());
  }
  
  /**
   * Tests login/logout process.
   * @throws Exception if error occurs.
   */
  @Test
  public void testLoginLogout() throws Exception {
    WebConversation conversation = new WebConversation();

    // Get redirected to login screen
    String Url = testHost + "myisern-fuchsia/login.jsp";
    WebResponse response = conversation.getResponse(Url);
    
    assertEquals("Checking arrival at login screen", pageTitle, response.getTitle());
    
    WebForm loginForm = response.getFormWithID("LoginForm");
    WebRequest loginRequest = loginForm.getRequest();
    loginRequest.setParameter("userName", "wrong");
    loginRequest.setParameter("password", "login");
    response = conversation.getResponse(loginRequest);
    
    assertEquals("Checking still at login screen", pageTitle, response.getTitle());
    
    loginRequest = loginForm.getRequest();
    loginRequest.setParameter("userName", "admin");
    loginRequest.setParameter("password", "changethis");
    response = conversation.getResponse(loginRequest);
    
    assertEquals("Checking arrival at displayTable.jsp", "ISERN - Display Data", 
        response.getTitle());
    
    loginForm = response.getFormWithID("logout");
    loginRequest = loginForm.getRequest();
    response = conversation.getResponse(loginRequest);
    assertEquals("Checking arrival at login screen", "MyISERN - Login", response.getTitle());
  }
  
}
